package com.hhit.zhgd.controller

import com.hhit.zhgd.component.FileProperties
import com.hhit.zhgd.domain.dto.BackStageAddArchiveFileMenuDTO
import com.hhit.zhgd.domain.entity.ZhgdArchiveSituation
import com.hhit.zhgd.domain.response.BaseResp
import com.hhit.zhgd.service.ZhgdArchiveSituationService
import jakarta.annotation.Resource
import jakarta.servlet.http.HttpServletResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

@RestController
class ZhgdArchiveSituationController {
    @Autowired
    private var zhgdArchiveSituationService: ZhgdArchiveSituationService? = null

    @Resource
    private val fileProperties:FileProperties?=null


    @PostMapping("/importArchiveFile")
    @Throws(Exception::class)
    fun importArchiveFile(@RequestParam("file") multipartFile:MultipartFile):BaseResp<Any?>? {
        return zhgdArchiveSituationService?.importArchiveFile(multipartFile)
    }

    @PostMapping("importArchiveFileNew")
    @Throws(java.lang.Exception::class)
    fun importArchiveFileNew(@RequestParam("file") multipartFile: MultipartFile?): BaseResp<Any?>? {
        return zhgdArchiveSituationService?.importArchiveFileNew(multipartFile)
    }

    /**
     * @description 后台管理-进度管理-上传归档文件至某个归档目录
     * @author qianchengcheng
     * @date 2024/7/2 13:56
     */
    @PostMapping("backStage/importArchiveSingleFile")
    @Throws(java.lang.Exception::class)
    fun importArchiveSingleFile(@RequestParam("file") multipartFile: MultipartFile?, @RequestParam("id") id: Int): BaseResp<Any?>? {
        return zhgdArchiveSituationService?.importArchiveSingleFile(multipartFile, id)
    }

    /**
     * @描述 批量导出
     * @参数 [ids, httpServletResponse]
     * @返回值 com.hhit.zhgd.utils.R
     * @创建人 qianchengcheng
     * @创建时间 2023/7/4
     * @修改人和其它信息
     */
    @PostMapping("/exportArchiveFiles")
    fun exportArchiveFiles(@RequestParam("ids") ids: List<Int?>?, response: HttpServletResponse): BaseResp<Any?>? {
        val zhgdArchiveSituations: List<ZhgdArchiveSituation> = zhgdArchiveSituationService?.listByIds(ids)?: listOf()
        val filePaths =
            zhgdArchiveSituations.map(ZhgdArchiveSituation::fileAddress).toList()
        // 设置响应头
        response.contentType = "application/octet-stream"
        response.setHeader("Content-Disposition", "attachment; filename=data_export.zip")
        try {
            response.outputStream.use { outputStream ->
                // 创建临时压缩文件
                val tempZipFile = Files.createTempFile("data_export", ".zip")
                // 压缩文件
                val zipOutputStream = ZipOutputStream(
                    Files.newOutputStream(tempZipFile),
                    StandardCharsets.UTF_8
                )
                // 添加文件到压缩文件
                for (filePath in filePaths) {
                    val file = File((fileProperties?.parentPath?:"") + filePath)
                    if (file.exists()) {
                        val zipEntry = ZipEntry(file.name)
                        zipOutputStream.putNextEntry(zipEntry)
                        val fileInputStream = FileInputStream(file)
                        val buffer = ByteArray(1024)
                        var length: Int
                        while (fileInputStream.read(buffer).also { length = it } > 0) {
                            zipOutputStream.write(buffer, 0, length)
                        }
                        fileInputStream.close()
                        zipOutputStream.closeEntry()
                    }
                }
                zipOutputStream.close()
                // 读取压缩文件并写入响应输出流
                val zipInputStream = FileInputStream(tempZipFile.toFile())
                val buffer = ByteArray(1024)
                var length: Int
                while (zipInputStream.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }
                zipInputStream.close()
                outputStream.flush()
            }
        } catch (e: IOException) {
            // 处理可能发生的文件输入/输出异常
//            log.error("ZhgdArchiveSituationController.exportArchiveFiles Call Error", e)
            return BaseResp.fail("下载文件失败:" + e.message)
        }
        return BaseResp.success()
    }

    /**
     * @描述 获取档案归档情况
     * @参数 []
     * @返回值 com.hhit.zhgd.utils.R
     * @创建人 qianchengcheng
     * @创建时间 2023/5/25
     * @修改人和其它信息
     */
    @GetMapping("/getArchiveFileInfo")
    fun getArchiveFileInfo(): BaseResp<Any?>? {
        return BaseResp.success(zhgdArchiveSituationService?.getArchiveFileInfo())
    }

    /**
     * @description 后台管理-进度管理-查询档案列表
     * @author qianchengcheng
     * @date 2024/7/1 17:04
     */
    @GetMapping("backStage/getArchiveFileMenuList")
    fun getArchiveFileMenuList(): BaseResp<Any?>? {
        return BaseResp.success(zhgdArchiveSituationService?.getArchiveFileMenuList())
    }

    /**
     * @description 后台管理-进度管理-新增档案菜单
     * @author qianchengcheng
     * @date 2024/7/1 17:34
     */
    @PostMapping("backStage/addArchiveFileMenu")
    fun addArchiveFileMenu(
        @RequestBody backStageAddArchiveFileMenuDTO: BackStageAddArchiveFileMenuDTO?,
        bindingResult: BindingResult
    ): BaseResp<Any?>? {
        if (bindingResult.hasErrors()) {
            val defaultMessage = bindingResult.fieldError?.defaultMessage
            return BaseResp.fail(defaultMessage)
        }
        return zhgdArchiveSituationService?.addArchiveFileMenu(backStageAddArchiveFileMenuDTO)
    }

    /**
     * @description 后台管理-进度管理-修改档案菜单
     * @author qianchengcheng
     * @date 2024/7/4 17:50
     */
    @PostMapping("backStage/editArchiveFileMenu")
    fun editArchiveFileMenu(
        @RequestBody backStageAddArchiveFileMenuDTO: BackStageAddArchiveFileMenuDTO?,
        bindingResult: BindingResult
    ): BaseResp<Any?>? {
        if (bindingResult.hasErrors()) {
            val defaultMessage = bindingResult.fieldError?.defaultMessage
            return BaseResp.fail(defaultMessage)
        }
        return zhgdArchiveSituationService?.editArchiveFileMenu(backStageAddArchiveFileMenuDTO)
    }

    /**
     * @description 后台管理-进度管理-删除档案菜单
     * @author qianchengcheng
     * @date 2024/7/1 17:38
     */
    @GetMapping("backStage/delArchiveFileMenu")
    fun delArchiveFileMenu(@RequestParam("id") id: Int?): BaseResp<Any?>? {
        return zhgdArchiveSituationService?.delArchiveFileMenu(id)
    }

    /**
     * @description 后台管理-进度管理-分页查询指定菜单下的文件列表
     * @author qianchengcheng
     * @date 2024/7/1 17:55
     */
    @GetMapping("backStage/getArchiveFilePageInfo")
    fun getArchiveFilePageInfo(
        @RequestParam(value = "id", required = false) id: Int?,
        @RequestParam(value = "keyWord") keyWord: String?,
        @RequestParam(value = "page", defaultValue = "1") page: Int,
        @RequestParam(value = "size", defaultValue = "15") size: Int
    ): BaseResp<Any?>? {
        return BaseResp.success(zhgdArchiveSituationService!!.getArchiveFilePageInfo(id, keyWord, page, size))
    }
}